from flask import Flask
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from config import Config
from routes.auth import auth_bp
from routes.device import device_bp

def create_app():
    app = Flask(__name__)
    
    # 加载配置
    app.config.from_object(Config)
    
    # 初始化CORS - 允许所有来源（开发环境）
    CORS(app, 
         origins=['*'],  # 临时允许所有来源
         allow_headers=['Content-Type', 'Authorization'],
         methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
    
    jwt = JWTManager(app)
    
    # 注册蓝图
    app.register_blueprint(auth_bp)
    app.register_blueprint(device_bp)
    
    # 健康检查接口
    @app.route('/api/health', methods=['GET'])
    def health_check():
        return {"status": "ok", "message": "Flask后端运行正常"}
    
    # 测试接口
    @app.route('/api/test', methods=['GET'])
    def test():
        return {
            "message": "后端连接成功！",
            "backend": "Flask",
            "version": "1.0.0"
        }
    
    return app

if __name__ == '__main__':
    app = create_app()
    print("=" * 50)
    print("智能家居管理系统 - Flask后端")
    print("=" * 50)
    print(f"后端服务器运行在: http://localhost:{Config.PORT}")
    print("测试账号:")
    print("  管理员: admin / 123456")
    print("  普通用户: user / 123456")
    print("=" * 50)
    
    app.run(host=Config.HOST, port=Config.PORT, debug=Config.DEBUG)